package com.ftg.elvis.service;

import com.ftg.elvis.mapper.AdminApplyMapper;
import com.ftg.elvis.pojo.Apply;
import com.ftg.elvis.pojo.Brand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AdminApplyService {

	@Autowired
	AdminApplyMapper adminApplyMapper;

	@Autowired
	AdminMailService adminMailService;

	public List<Apply> showAll(int page, int limit, String aname, String astate) {
		page = (page - 1) * limit;
		aname = aname == null ? "" : aname;
		astate = "".equals(astate) ? null : astate;

		return adminApplyMapper.showAll(page, limit, aname, astate);
	}

	public int getCount(String aname, String astate) {
		aname = aname == null ? "" : aname;
		astate = "".equals(astate) ? null : astate;
		return adminApplyMapper.getCount(aname, astate);
	}

	public List<Apply> findByState(int page, int limit, String astate) {
		page = (page - 1) * limit;
		astate = "".equals(astate) ? null : astate;
		return adminApplyMapper.findByState(page, limit, astate);
	}

	public int getCountByState(String astate) {
		astate = "".equals(astate) ? null : astate;
		return adminApplyMapper.getCountByState(astate);
	}

	@Transactional
	public int updateState(String astate, String aid) throws Exception{
		//如果要将状态改为审核通过就将其添加进品牌表
			if("审核通过".equals(astate)){
				//修改状态为审核通过
				adminApplyMapper.updateState(astate, aid);

				//查询出该品牌信息
				Apply apply = adminApplyMapper.findByAid(aid);

				//给该品牌发送邮件
				//MailUtil.sendMail(apply);
				adminMailService.sendMail(apply);

				//把Brand加入品牌表
				saveApplyToBrandByAid(aid);
			}else{
				adminApplyMapper.updateState(astate, aid);

				//查询出该品牌信息
				Apply apply = adminApplyMapper.findByAid(aid);

				//给该品牌发送邮件
				//MailUtil.sendMail(apply);
				adminMailService.sendMail(apply);
			}
		return 1;
	}

	private int saveApplyToBrandByAid(String aid){
		//按照aid将Apply查出，
		Apply apply = adminApplyMapper.findByAid(aid);

		//将Apply属性响应赋给Brand
		Brand brand = new Brand();
		brand.setBid(apply.getAid());
		brand.setBname(apply.getAname());
		brand.setBlogo(apply.getAlogo());
		brand.setBinfo(apply.getAinfo());
		brand.setBtel(apply.getPhone());
		brand.setBwebsite(apply.getAwebsite());
		brand.setBstate(apply.getAstate());
		brand.setUsername(apply.getUsername());
		brand.setEmail(apply.getAemail());

		//把Brand加入品牌表
		return adminApplyMapper.saveApplyToBrand(brand);
	}

	public int delete(String aid) {
		return adminApplyMapper.delete(aid);
	}
}
